package com.vuestart.shushan.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.vuestart.common.to.OrderTo;
import com.vuestart.common.to.StockDetailTo;
import com.vuestart.common.to.mq.StockLockedTo;
import com.vuestart.common.utils.R;
import com.vuestart.shushan.ware.entity.WareOrderTaskDetailEntity;
import com.vuestart.shushan.ware.entity.WareOrderTaskEntity;
import com.vuestart.shushan.ware.service.WareSkuService;
import com.vuestart.shushan.ware.vo.OrderVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @创建：--> DKD <--
 * @日期： 2021-04-24 11:19
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue") // 监听队列
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    // 库存解锁功能
    /**
     * 告诉mq不要自动删除ack 所以彳亍调成 手动ack
     *
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handlerStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        try{
            // 当前消息是否被第二次及以后（重新）派发过来的 ↓↓↓↓↓↓↓
//            Boolean redelivered = message.getMessageProperties().getRedelivered();
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            // 有任何异常消息放回队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    // todo 忘了加 @RabbitHandler 注解。。。
    @RabbitHandler
    public void HandleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("收到订单关闭的消息，准备解锁库存");
        try{
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

    }

}
